package com.laomuji.android.mvvm.demo.h5

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.webkit.ConsoleMessage
import android.webkit.JsResult
import android.webkit.WebChromeClient
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AlertDialog
import com.laomuji.android.mvvm.base.BaseActivity
import com.laomuji.android.mvvm.base.BaseActivityViewModel
import com.laomuji.android.mvvm.databinding.ActivityH5Binding
import com.laomuji.android.mvvm.http.common.GsonManager
import com.laomuji.android.mvvm.utils.MyLog
import com.laomuji.android.mvvm.utils.PackageUtil
import com.laomuji.android.mvvm.utils.ResourceUtil

/**
 * H5页面
 * @author laomuji666
 * @since 2024/2/27
 */
class H5Activity:BaseActivity<ActivityH5Binding,BaseActivityViewModel>() {
    companion object{
        const val H5_URL = "h5_url"

        fun openH5Activity(url:String?){
            val topActivity = PackageUtil.getTopActivity()
            val it = Intent(topActivity,H5Activity::class.java)
            it.putExtra(H5_URL,url)
            topActivity.startActivity(it)
        }
    }


    override fun initView() {
        viewBinding.root.setPadding(0, ResourceUtil.getStatusBarHeight(), 0, 0)
        initH5()
        initBackPressed()
    }

    override fun initData() {
        viewBinding.wvH5.loadUrl(intent.getStringExtra(H5_URL) ?: "https://www.google.com")
    }

    /**
     * 为WebView添加一些参数
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun initH5() {
        //配置一些参数
        val settings: WebSettings = viewBinding.wvH5.settings
        //开启JavaScript,不安全
        settings.javaScriptEnabled = true
        //允许打开窗口
        settings.javaScriptCanOpenWindowsAutomatically = true
        //开启Dom支持,不安全
        settings.domStorageEnabled = true
        //支持缩放
        settings.setSupportZoom(true)
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        //混合加载网络协议
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        //允许多窗口
        viewBinding.wvH5.settings.setSupportMultipleWindows(true)
        //允许播放视频
        viewBinding.wvH5.settings.mediaPlaybackRequiresUserGesture = false

        //添加webViewClient,禁止跳转到浏览器,在当前WebView显示
        viewBinding.wvH5.webViewClient = CustomWebViewClient()

        //添加webChromeClient,对浏览器内核进行一些操作
        viewBinding.wvH5.webChromeClient = CustomWebChromeClient()


        //添加js接口,被h5调用
        //如:h5可以使用window.h5_interface.openWebView(url)来打开一个新的WebView页面
        viewBinding.wvH5.addJavascriptInterface(H5Interface(), "h5_interface")
    }


    /**
     * 按下返回键回到WebView的上一页
     */
    private fun initBackPressed(){
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true){
            override fun handleOnBackPressed() {
                if (viewBinding.wvH5.canGoBack()){
                    viewBinding.wvH5.goBack()
                }else{
                    finish()
                }
            }
        })
    }

    /**
     * 拦截返回键
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if(keyCode == KeyEvent.KEYCODE_BACK  && viewBinding.wvH5.canGoBack()){
            onBackPressedDispatcher.onBackPressed()
            true
        }else{
            super.onKeyDown(keyCode, event)
        }
    }


    inner class CustomWebChromeClient : WebChromeClient() {
        //打印h5的控制台日志
        override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
            MyLog.iCustom("tag_h5", GsonManager.gson.toJson(consoleMessage))
            return super.onConsoleMessage(consoleMessage)
        }

        //网页加载进度
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            //显示加载进度
            if (newProgress > 99) {
                viewBinding.sbSeek.visibility = View.GONE
                viewBinding.ivLoading.visibility = View.GONE
            } else {
                viewBinding.sbSeek.progress = newProgress
                viewBinding.sbSeek.visibility = View.VISIBLE
                viewBinding.ivLoading.visibility = View.VISIBLE
            }
        }

        //拦截alert,显示自定义的弹窗
        override fun onJsAlert(
            webView: WebView?,
            url: String?,
            message: String?,
            jsResult: JsResult
        ): Boolean {
            val builder: AlertDialog.Builder = AlertDialog.Builder(this@H5Activity)
            builder.setMessage(message).setPositiveButton("OK") { arg0, _ -> arg0.dismiss() }.show()
            jsResult.confirm()
            return true
        }

        //拦截打开新窗口
        override fun onCreateWindow(
            view: WebView?,
            isDialog: Boolean,
            isUserGesture: Boolean,
            resultMsg: Message
        ): Boolean {
            val tempWebView = WebView(this@H5Activity)
            tempWebView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView,
                    request: WebResourceRequest
                ): Boolean {
                    openH5Activity(request.url.toString())
                    return true
                }
            }
            val transport = resultMsg.obj as WebView.WebViewTransport
            transport.webView = tempWebView
            resultMsg.sendToTarget()
            return true
        }
    }

    inner class CustomWebViewClient : WebViewClient(){
        @Deprecated("Deprecated in Java")
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            if (url.startsWith("http") || url.startsWith("https")) {
                //拦截http和https,不允许跳转
                view.loadUrl(url)
                return true
            } else {
                //其它协议直接跳转
                try {
                    val it = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(it)
                    viewBinding.wvH5.visibility = View.GONE
                    finish()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return false
        }
    }
}